package com.atguigu.bigdata.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.edu.realtime.app.BaseAppV1;
import com.atguigu.bigdata.edu.realtime.bean.TradeProvinceOrder;
import com.atguigu.bigdata.edu.realtime.common.Constant;
import com.atguigu.bigdata.edu.realtime.function.DimAsyncFunction;
import com.atguigu.bigdata.edu.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;


public class Dws_10_DwsTradeProvinceOrderWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_10_DwsTradeProvinceOrderWindow().init(
            4010,
            2,
            "Dws_10_DwsTradeProvinceOrder",
            Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {

        // 1. 解析成一个 pojo
        SingleOutputStreamOperator<TradeProvinceOrder> beanStream = parseToPojo(stream);
        // 2. 开窗聚和
        SingleOutputStreamOperator<TradeProvinceOrder> beanStreamWithoutDim = windowAndAgg(beanStream);
        // 3. 补充维度: 旁路缓存优化和异步优化
        SingleOutputStreamOperator<TradeProvinceOrder> resultStream = joinDim(beanStreamWithoutDim);
        // 4. 写出到 clickhouse 中
        writeToClickHouse(resultStream);
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TradeProvinceOrder> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_province_order_window", TradeProvinceOrder.class));
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrder> joinDim(SingleOutputStreamOperator<TradeProvinceOrder> stream) {
      return  AsyncDataStream.unorderedWait(
            stream,
            new DimAsyncFunction<TradeProvinceOrder>(){
                @Override
                public String table() {
                    return "dim_base_province";
                }
    
                @Override
                public String id(TradeProvinceOrder input) {
                    return input.getProvinceId();
                }
    
                @Override
                public void addDim(JSONObject dim, TradeProvinceOrder input) {
                    input.setProvinceName(dim.getString("NAME"));
                }
            },
            120,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrder> windowAndAgg(SingleOutputStreamOperator<TradeProvinceOrder> beanStream) {
       return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeProvinceOrder>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> {
                        System.out.println("ts: " + ts);
                        return bean.getTs();
                    })
            )
            .keyBy(TradeProvinceOrder::getProvinceId)
            .window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeProvinceOrder>() {
                    @Override
                    public TradeProvinceOrder reduce(TradeProvinceOrder value1,
                                                           TradeProvinceOrder value2) throws Exception {
                        // 把 value2 中的order_id 都存入到 value1 中的 set 集合中
                        value1.getOrderIdSet().addAll(value2.getOrderIdSet());
                        value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeProvinceOrder, TradeProvinceOrder, String, TimeWindow>() {
                    @Override
                    public void process(String provinceId,
                                        Context ctx,
                                        Iterable<TradeProvinceOrder> elements,
                                        Collector<TradeProvinceOrder> out) throws Exception {
                        TradeProvinceOrder bean = elements.iterator().next();
                        
                        bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));
    
                        bean.setOrderCount((long) bean.getOrderIdSet().size());
    
                        bean.setTs(System.currentTimeMillis());
                        
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradeProvinceOrder> parseToPojo(
        SingleOutputStreamOperator<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj->obj.getString("province_id"))
                .map(new RichMapFunction<JSONObject, TradeProvinceOrder>() {
                    private ValueState<Set<String>> userIdState;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        userIdState = getRuntimeContext().getState(new ValueStateDescriptor<Set<String>>("userIdState", TypeInformation.of(new TypeHint<Set<String>>() {
                        })));
                    }

                    @Override
                    public TradeProvinceOrder map(JSONObject obj) throws Exception {
                        String provinceId = obj.getString("province_id");
                        HashSet<String> orderIdSet = new HashSet<>();
                        orderIdSet.add(obj.getString("order_id"));
                        BigDecimal orderAmount = obj.getBigDecimal("final_amount");
                        Long ts = obj.getLong("ts")*1000;

                        HashSet<String> userIdSet = new HashSet<>();
                        String userId = obj.getString("user_id");
                        userIdSet.add(userId);
                        Long newUser=0L;
                        Set<String> userSet = userIdState.value();
                        if(userSet == null){
                            HashSet<String> set = new HashSet<>();
                            set.add(userId);
                            userIdState.update(set);
                            newUser = 1L;
                        }else if(!userSet.contains(userId) ){
                            userSet.add(userId);
                            newUser = 1L;
                        }

                        return new TradeProvinceOrder("", "", provinceId, "", orderIdSet, userIdSet, orderAmount, 0L, 0L, newUser, ts);
                    }
                });
    }

}
